#!/usr/bin/env python3
"""
libstoragemgmt MCP Server

面向 libstoragemgmt 存储管理软件的 MCP 服务器，提供命令行操作封装。

MCP tools 列表：
1. libstoragemgmt_service_control - 控制 libstoragemgmt 服务状态
   用途：启动、重启、重载、查看 libstoragemgmt 服务状态
   参数：action (str): 操作类型，支持 'start', 'restart', 'reload', 'status'
   返回：统一 JSON 结构

2. libstoragemgmt_service_edit - 编辑 libstoragemgmt 服务配置
   用途：修改 libstoragemgmt 服务的 systemd 配置文件
   参数：search_pattern (str): 要搜索的文本模式
        replace_pattern (str): 要替换的文本模式
   返回：统一 JSON 结构
"""

from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Dict, Any

mcp = FastMCP("libstoragemgmt MCP Server")

@mcp.tool()
def libstoragemgmt_service_control(action: str) -> Dict[str, Any]:
    """
    控制 libstoragemgmt 服务状态
    
    参数:
        action: 操作类型，支持 'start', 'restart', 'reload', 'status'
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    valid_actions = ['start', 'restart', 'reload', 'status']
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} libstoragemgmt.service",
            "exit_code": 1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Supported actions: {valid_actions}"
        }
    
    if action == 'reload':
        # 对于 reload 操作，需要先执行 daemon-reload
        cmd1 = ["systemctl", "daemon-reload"]
        cmd2 = ["systemctl", "reload", "libstoragemgmt.service"]
        
        result1 = subprocess.run(cmd1, capture_output=True, text=True)
        result2 = subprocess.run(cmd2, capture_output=True, text=True)
        
        return {
            "success": result1.returncode == 0 and result2.returncode == 0,
            "command": f"{' '.join(cmd1)} && {' '.join(cmd2)}",
            "exit_code": result2.returncode,
            "stdout": f"daemon-reload: {result1.stdout}\nreload: {result2.stdout}",
            "stderr": f"daemon-reload: {result1.stderr}\nreload: {result2.stderr}"
        }
    else:
        cmd = ["systemctl", action, "libstoragemgmt.service"]
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }

@mcp.tool()
def libstoragemgmt_service_edit(search_pattern: str, replace_pattern: str) -> Dict[str, Any]:
    """
    编辑 libstoragemgmt 服务的 systemd 配置文件
    
    参数:
        search_pattern: 要搜索的文本模式
        replace_pattern: 要替换的文本模式
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    service_file = "/usr/lib/systemd/system/libstoragemgmt.service"
    cmd = ["sed", "-i", f"s\\{search_pattern}\\{replace_pattern}\\g", service_file]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True)
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": 1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()